from django.db.models import Q
from rest_framework import serializers

from goods.models import Goods, GoodsCategory, GoodsImage, Banner, GoodsCategoryBrand, IndexAd


class GoodsCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"


class GoodsImageSerializer(serializers.ModelSerializer):
    """
    商品图片序列化
    """
    class Meta:
        model = GoodsImage
        fields = ("image",)


class GoodsSerializer(serializers.ModelSerializer):
    # 嵌套外键的字段
    category = GoodsCategorySerializer()
    images = GoodsImageSerializer(many=True)

    class Meta:
        model = Goods
        fields = "__all__"

    def create(self, validated_data):
        """
        Create and return a new `Goods` instance, given the validated data.
        """
        return Goods.objects.create(**validated_data)


class ThreeCategorySerializer(serializers.ModelSerializer):
    """"
    商品三级类目序列化
    """

    class Meta:
        model = GoodsCategory
        fields = "__all__"


class TwoCategorySerializer(serializers.ModelSerializer):
    """"
    商品二级类目序列化
    """
    sub_cat = ThreeCategorySerializer(many=True)

    class Meta:
        model = GoodsCategory
        fields = "__all__"


class OneCategorySerializer(serializers.ModelSerializer):
    """"
    商品一级类目序列化
    """
    sub_cat = TwoCategorySerializer(many=True)

    class Meta:
        model = GoodsCategory
        fields = "__all__"


class BannerSerializer(serializers.ModelSerializer):
    """"
    商品轮播图序列化
    """
    class Meta:
        model = Banner
        fields = "__all__"


class BrandSerializer(serializers.ModelSerializer):
    """"
    品牌名序列化
    """
    class Meta:
        model = GoodsCategoryBrand
        fields = "__all__"


class IndexCategorySerializer(serializers.ModelSerializer):
    """"
    首页商品序列化
    """
    brands = BrandSerializer(many=True)
    goods = serializers.SerializerMethodField()
    sub_cat = TwoCategorySerializer(many=True)
    ad_goods = serializers.SerializerMethodField()

    def get_ad_goods(self, obj):
        goods_json = {}
        ad_goods = IndexAd.objects.filter(category_id=obj.id)
        if ad_goods:
            good_ins = ad_goods[0].goods
            goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data
        return goods_json

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) | Q(category__parent_category_id=obj.id) | Q(
            category__parent_category_id__parent_category_id=obj.id))
        # 嵌套serializer需要传递context={'request': self.context['request']}
        goods_serializer = GoodsSerializer(all_goods, many=True, context={'request': self.context['request']})
        return goods_serializer.data

    class Meta:
        model = GoodsCategory
        fields = "__all__"